package com.hj.system.base.aspect;

import com.hj.system.base.annotation.CacheRemove;
import com.hj.system.base.config.ApplicationContextRegister;
import net.sf.ehcache.Ehcache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class CacheRemoveAspect {

    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    //两个..代表所有子目录，最后括号里的两个..代表所有参数
    @Pointcut("execution( * com.hj..impl.*.*(..))&& @annotation(com.hj.system.base.annotation.CacheRemove))")
    public void logPointCut() {
    }


    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
        if (cacheRemove != null) {
            String value = cacheRemove.value();
            String[] keys = cacheRemove.key(); //需要移除的正则key
            remove(value, keys);
        }
    }

    private void remove(String value, String[] keys) {
        EhCacheCacheManager ehCacheCacheManager = ApplicationContextRegister.getBean(EhCacheCacheManager.class);
        net.sf.ehcache.CacheManager cacheManager = ehCacheCacheManager.getCacheManager();
        Ehcache ehcache = cacheManager.getEhcache(value);
        List<String> origin_keys = ehcache.getKeys();
        for (String key : keys) {
            for (String o_key : origin_keys) {
                if (o_key.startsWith(key)) {
                    ehcache.remove(o_key);
                }
            }
        }
    }


}
